<template>
	<div id="consultation" style="display: flex;">
		<div style="flex: 2; margin: 10px;">
			<h2 style="color: #097E7E;">基本信息</h2>
			<v-table :tableData="tableData" :tableColumns="tableColumns"></v-table>
		</div>
		<!--<p class="time"><span>11:12</span></p>-->
		<div id="chat" style="flex: 3; margin: 10px; min-width: 500px;">
			<div class="main">
				<div class="header">
					{{obj.name}}
				</div>
				<div class="m-message" id="myData" ref='message'>
					<ul>
						<li v-for="item in dataArr">
							<!-- 根据 is_user 判断是我说的话还是对方说的话     1：对方说的话， 2：我说的话-->
							<div class="main" v-if="item.is_user === 1">
								<!-- 判断有没有头像，没有头像就像是默认的头像 -->
								<img :src="item.face" alt="" style="width: 30px;height: 30px; float: left;" />
								<img class="avatar" v-if="item.face == '' || item.face == null" src="https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1537261917&di=bbc0c768ba2e9ab1b45a75bd42a422ef&src=http://tx.haiqq.com/uploads/allimg/170810/0430103R0-3.jpg" alt="" />

								<div class="text demo-upload-list" ref='list'>
									{{item.content}}
									<!-- 显示图片 -->
									<div v-if="item.imageUrl !== ''">
										<img :src="item.imageUrl" alt="" style="width: 60px;" />
										<div class="demo-upload-list-cover">
											<Icon type="ios-eye-outline" @click.native="handleView(item.imageUrl)"></Icon>
										</div>
									</div>
									<Modal title="查看图片" v-model="visible" :footer-hide="true" :width="400">
										<img :src="imgUrl" style="width: 100%">
									</Modal>
								</div>
							</div>
							<div class="main self" v-else>
								<!-- 判断有没有头像，没有头像就像是默认的头像 -->
								<!--<img :src="item.face" alt="" />-->
								<img class="avatar" src="https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1537261917&di=bbc0c768ba2e9ab1b45a75bd42a422ef&src=http://tx.haiqq.com/uploads/allimg/170810/0430103R0-3.jpg" alt="" />

								<div class="text">
									{{item.content}}
									<img :src="item.imageUrl" alt="" width="100px" />
								</div>

							</div>
						</li>

						<!--<div class="main text" v-show="isShow" v-for="item in websockArr">
							<img class="avatar" src="https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1537261917&di=bbc0c768ba2e9ab1b45a75bd42a422ef&src=http://tx.haiqq.com/uploads/allimg/170810/0430103R0-3.jpg" alt="" />
								
							<div class="text">
								{{item.text}}
							</div>
						</div>-->
					</ul>
				</div>

				<div class="m-text">
					<quill-editor ref="myQuillEditor" v-model="newItem" :options="editorOption" @change="onEditorChange">
					</quill-editor>
					<!-- 文件上传input 将它隐藏-->
					<Upload class="upload-demo" action="/upload/image" :before-upload='beforeUpload' :on-success='upScuccess' :data="images" ref="upload" style="display:none">
						<Button size="small" type="primary" id="imgInput">点击上传</Button>
					</Upload>
					<Button class="btn" @click="seed">发送</Button>
				</div>

			</div>
		</div>

	</div>
</template>
<script>
	import Quill from 'quill'
	import vTable from '@/components/common/Table.vue';
	// 富文本编辑
	import { quillEditor } from 'vue-quill-editor'
	import { quillRedefine } from 'vue-quill-editor-upload'
	var timer = null;
	export default {
		components: {
			quillEditor,
			vTable
		},
//		inject: ['reload'],
		data() {
			return {
				dataList: [],
				header: '',
				visible: false,
				websockArr: [],
				tableData: [],
				tableColumns: [{
						title: '姓名',
						key: 'realName',
						align: "center"
					},
					{
						title: '性别',
						key: 'gender',
						align: "center"
					},
					{
						title: '年龄',
						key: 'age',
						align: "center"
					},
					{
						title: '操作',
						key: 'action',
						width: 150,
						align: 'center',
						render: (h, params) => {
							return h('div', [
								h('Button', {
									props: {
										type: 'primary',
										size: 'small'
									},
									style: {
										marginRight: '5px'
									},
									on: {
										click: () => {
											this.$router.push({
												path: '/user/personal/edit/' + params.row.id,
												query: params.row.id
											});
										}
									}
								}, '查看')
							]);
						}
					}
				],
				isShow: true,
				websock: null,
				websockVal: '',
				editorOption: {
					placeholder: '',
					theme: 'snow',
					modules: {
						toolbar: [
							['image'] //
						]
					}
				},
				dataArr: [],
				timer: '',
				newItem: '',
				images: {
					type: 4,
					image: null
				},
				uploadType: '', // 上传的文件类型（图片、视频）
				addRange: [],
				replayData: {
					avatar: '', // 头像
					content: '', //内容
					fatherid: '', //回复父id
					imageurl: '', //回复图片
					topicid: '', //  当前咨询标题id
					posterId: '', //当前回复者id
					isUser: 2 //回复者1：为用户，2：管理师
				},
				obj: {

				},
				imgUrl: '',
				img: '',

			}
		},
		watch: {
			//  监听dataArr数据，每次添加后滚动到底部
			dataArr(val) {
				this.$nextTick(() => {
					let list = this.$refs.message
					list.scrollTop = list.scrollHeight
				})
			},
		},
		methods: {
			// 点击图片，放大
			handleView(imgUrl) {
				this.imgUrl = imgUrl;
				this.visible = true
			},
			onEditorChange(val) {
				//				console.log(val.text)
				this.replayData.content = val.text;
				//				this.replayData.content = this.newItem;
			},
			// 这个钩子还支持 promise
			beforeUpload(file) {
				this.images.image = file
				//				return this.qnUpload(file)
			},
			// 图片上传成功回调 插入到编辑器中
			upScuccess(e, file, fileList) {
				console.log(e)
				this.imgUrl = 'http://dxyisudai.com' + e.data.path;
				//				this.replayData.imageurl = 'http://dxyisudai.com' + e.data.path;
				let vm = this
				let url = this.imgUrl;
				if(url != null && url.length > 0) { // 将文件上传后的URL地址插入到编辑器文本中
					let value = url
					// API: https://segmentfault.com/q/1010000008951906
					// this.$refs.myTextEditor.quillEditor.getSelection();
					// 获取光标位置对象，里面有两个属性，一个是index 还有 一个length，这里要用range.index，即当前光标之前的内容长度，然后再利用 insertEmbed(length, 'image', imageUrl)，插入图片即可。
					vm.addRange = vm.$refs.myQuillEditor.quill.getSelection()
					value = value.indexOf('http') !== -1 ? value : 'http:' + value
					vm.$refs.myQuillEditor.quill.insertEmbed(vm.addRange !== null ? vm.addRange.index : 0, vm.uploadType, value, Quill.sources.USER) // 调用编辑器的 insertEmbed 方法，插入URL
				} else {
					this.$message.error(`${vm.uploadType}插入失败`)
				}
				this.$refs['upload'].clearFiles() // 插入成功后清除input的内容
			},
			// 点击图片ICON触发事件
			imgHandler(state) {
				this.addRange = this.$refs.myQuillEditor.quill.getSelection()
				//				console.log(this.addRange)
				if(state) {
					let fileInput = document.getElementById('imgInput')
					fileInput.click() // 加一个触发事件
				}
				this.uploadType = 'image'
			},
			// 发送信息 
			sendData() {
				//   因为vue-quill-editor富文本编辑框出现  <p></p>,所以需要去掉 <p></p>
				if(this.newItem.indexOf('img') === 4) {
					this.replayData.imageurl = this.newItem.split(' ')[1].split('=')[1].split('></p>')[0].split('"')[1]
				} else {
					//					this.newItem = this.newItem.split('<p>')[1].split('</p>')[0];
					//					this.replayData.content = this.newItem; //   将textarea 输入的值 赋给 this.replayData.content
				}
				this.newItem = ''; //  点击发送清空
				console.log(this.replayData)
				this.$http.post('/topic/addComment', this.replayData)
					.then((res) => {
						this.replayData.imageurl = '' //  发送完  图片清空
						this.replayData.content = '' //  发送完 内容清空
						console.log(res)
						//						this.reload()
						this.getData2(); //  发送完 获取咨询记录  getData2()
					})
					.catch((err) => {
						console.log(err);
					})
			},
			// 获取咨询记录
			getData2() {
				this.$http.get('/topic/record_' + this.obj.id)
					.then(({data}) => {
						this.replayData.topicid = data.data.topic.id; //  赋值给  replayData.topicid
						this.dataArr = data.data.comment.list;
						let arr = this.dataArr.slice(this.dataArr.length - 1); // 拿到最后一个对象的 comment_id
						if(arr.length !== 0) {
							this.replayData.fatherid = arr[0].comment_id;
							this.dataArr.map(e => {
								if(e.is_user == null) {
									e.is_user = 1
								}
							})
						}
						//						console.log(this.dataArr)
					})
					.catch((err) => {
						console.log(err);
					})
			},
			//  获取基本信息  
			getData3() {
				this.$http.get('/topic/topic_customer_list/' + this.$route.query.id)
					.then(({data}) => {
						//						console.log(data)
						this.tableData = data.data.map(e => {
							if(e.gender === 1) {
								e.gender = '男'
							} else if(e.gender === 2) {
								e.gender = '女'
							}
							return e;
						})
						//					console.log(this.tableData)	
					})
					.catch((err) => {
						console.log(err);
					})
			},
			// 点击发送
			seed() {
				console.log(this.replayData)
				if(this.$refs.myQuillEditor.value === '') {
					this.$Message.error('不能发送空白信息');
				} else {
					console.log(this.replayData.content)
					//					console.log(this.newItem)
					this.sendData(); //    请求接口， 传参给后台
				}
			},

		},
		created() {
			this.replayData.posterId = localStorage.getItem('user_id');
			this.obj = this.$route.query;
			this.getData2(); //  初始化咨询记录

			console.log(this.$route.query)
			localStorage.setItem('obj', JSON.stringify(this.obj))
			this.getData3() //  获取基本信息  

			//  处理图片
			this.$refs = {
				myQuillEditor: HTMLInputElement,
				imgInput: HTMLInputElement
			}
		},
		mounted() {
			// 为图片ICON绑定事件 getModule 为编辑器的内部属性
			this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler)

			this.$watch('dataArr', function(newVal, oldVal) {
				clearInterval(timer)
				timer = setInterval(() => {
					this.getData2()
				}, 3000)
//				console.log(this.dataArr)
			})
		}
	}
</script>

<style scoped>
	.header {
		color: #000;
		background: #eee;
		height: 40px;
		line-height: 40px;
		text-align: center;
		margin-bottom: 10px;
		border: 1px solid #ccc;
		font-size: 18px;
	}
	
	.demo-upload-list {
		display: inline-block;
		/*width: 60px;*/
		height: auto;
		text-align: center;
		line-height: 60px;
		border: 1px solid transparent;
		border-radius: 4px;
		overflow: hidden;
		background: #fff;
		position: relative;
		box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
		margin-right: 4px;
		z-index: 1;
		margin-bottom: 20px;
	}
	
	.demo-upload-list img {
		width: 100%;
		height: 100%;
		z-index: 99;
	}
	
	.demo-upload-list-cover {
		display: none;
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		background: rgba(55, 55, 55, .6);
		z-index: 999999;
	}
	
	.demo-upload-list:hover .demo-upload-list-cover {
		display: block;
		z-index: 999999;
	}
	
	.demo-upload-list-cover i {
		width: 30px;
		height: 30px;
		color: #fff;
		font-size: 20px;
		cursor: pointer;
		z-index: 999999;
		position: absolute;
		left: 50%;
		top: 50%;
		margin-left: -10px;
		margin-top: -15px;
	}
	
	.main.text {
		width: 100%;
		margin-bottom: 10px;
	}
	
	.ivu-upload {
		border: 0 !important;
	}
	
	ul,
	li {
		list-style: none;
	}
	
	#chat {
		margin: 20px auto;
		width: 600px;
		height: 630px;
		box-shadow: 0px 0px 20px #f1f1f1;
	}
	
	#chat .main {
		height: 100%;
	}
	
	#chat .main {
		position: relative;
		overflow: hidden;
		background-color: #eee;
	}
	
	#chat .m-message {
		height: calc(100% - 12.6pc);
	}
	
	.m-message {
		padding: 10px 15px;
		overflow-y: scroll;
	}
	
	.m-message li {
		margin-bottom: 15px;
	}
	
	.m-message .time {
		margin: 7px 0;
		text-align: center;
	}
	
	.m-message .time>span {
		display: inline-block;
		padding: 0 18px;
		font-size: 9pt;
		color: #fff;
		border-radius: 2px;
		background-color: #dcdcdc;
	}
	
	.m-message .avatar {
		float: left;
		margin: 0 10px 0 0;
		border-radius: 3px;
		width: 30px;
		height: 30px;
	}
	
	.m-message .text {
		display: inline-block;
		position: relative;
		padding: 0 10px;
		max-width: calc(101% - 40px);
		min-height: 30px;
		line-height: 2.5;
		font-size: 9pt;
		text-align: left;
		word-break: break-all;
		background-color: #fafafa;
		border-radius: 4px;
		margin-left: 10px;
	}
	
	/*.m-message .text:before {
		content: " ";
		position: absolute;
		top: 9px;
		right: 100%;
		border: 6px solid transparent;
		border-right-color: #fafafa;
	}*/
	
	.m-message .self {
		text-align: right;
	}
	
	.m-message .self .avatar {
		float: right;
		margin: 0 0 0 10px;
	}
	/* 输入框 */
	
	#chat .m-text {
		position: absolute;
		width: 100%;
		bottom: 0;
		left: 0;
	}
	/*.m-text {
		height: 8pc;
	}*/
	
	.m-text textarea {
		padding: 10px;
		height: 100%;
		width: 100%;
		border: none;
		outline: 0;
		font-family: Micrsofot Yahei;
		resize: none;
		background: #fff;
		border: 1px solid #eee;
		border-top: none;
		padding-top: 28px;
	}
	
	.btn {
		position: absolute;
		right: 24px;
		bottom: 10px;
	}
	/*  图片上传 */
	
	.seedPic {
		padding-left: 10px;
		position: relative;
		top: 33px;
		left: 0;
		z-index: 999;
	}
</style>